package org.ziegler.netty.cp8;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.net.DatagramPacket;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

public class DatagramTest {

    public static void main(String[] args) throws InterruptedException {
        DatagramTest datagramTest = new DatagramTest();
        datagramTest.client(8887);
    }

    void client(int port) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup())
                .option(ChannelOption.SO_BROADCAST, true)
                .channel(NioDatagramChannel.class)
                .remoteAddress(new InetSocketAddress("255.255.255.255", port))
                .handler(new SimpleChannelInboundHandler<ByteBuf>() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                super.channelActive(ctx);
                System.out.println("DatagramTest.channelActive");
            }

            @Override
            protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                System.out.println("DatagramTest.channelRead0" + msg);
            }
        });;

        Channel channel = bootstrap.bind(0).sync().channel();

        byte[] msg = "ddd".getBytes();

        while (true) {
            channel.writeAndFlush(new DatagramPacket(msg, msg.length,
                    new InetSocketAddress("255.255.255.255", port)));

            System.out.println("发送消息包");

            Thread.sleep(1000);
        }

    }


}
